// 圣经问答游戏 - 简单音频系统

class SimpleAudioSystem {
    constructor() {
        this.sounds = {};
        this.enabled = true;
        this.volume = 0.5;
        this.createSounds();
    }

    // 创建音效（使用Data URL编码的简短音频）
    createSounds() {
        // 创建简单的音效 - 使用短暂的正弦波
        this.sounds = {
            correct: this.createBeepSound([523, 659, 784], 300), // 愉快和弦
            wrong: this.createBeepSound([220], 400),              // 低音
            achievement: this.createBeepSound([262, 330, 392, 523], 200), // 上升音阶
            click: this.createBeepSound([800], 100)               // 短促提示音
        };
    }

    // 创建蜂鸣音效
    createBeepSound(frequencies, duration) {
        return () => {
            if (!this.enabled) return;
            
            frequencies.forEach((freq, index) => {
                setTimeout(() => {
                    this.playBeep(freq, duration / frequencies.length);
                }, index * (duration / frequencies.length));
            });
        };
    }

    // 播放蜂鸣音
    playBeep(frequency, duration) {
        try {
            // 使用Web Audio API
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();

            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);

            oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
            oscillator.type = 'sine';

            const now = audioContext.currentTime;
            gainNode.gain.setValueAtTime(0, now);
            gainNode.gain.linearRampToValueAtTime(this.volume * 0.1, now + 0.01);
            gainNode.gain.exponentialRampToValueAtTime(0.001, now + duration / 1000);

            oscillator.start(now);
            oscillator.stop(now + duration / 1000);
        } catch (error) {
            // 降级到传统方法
            this.playBeepFallback(frequency, duration);
        }
    }

    // 降级蜂鸣音方法
    playBeepFallback(frequency, duration) {
        try {
            // 创建一个短暂的音频元素
            const audio = new Audio();
            
            // 生成简单的音频数据URL（这是一个非常基础的实现）
            const sampleRate = 8000;
            const samples = Math.floor(sampleRate * duration / 1000);
            const buffer = new ArrayBuffer(44 + samples * 2);
            const view = new DataView(buffer);
            
            // WAV文件头
            const writeString = (offset, string) => {
                for (let i = 0; i < string.length; i++) {
                    view.setUint8(offset + i, string.charCodeAt(i));
                }
            };
            
            writeString(0, 'RIFF');
            view.setUint32(4, 36 + samples * 2, true);
            writeString(8, 'WAVE');
            writeString(12, 'fmt ');
            view.setUint32(16, 16, true);
            view.setUint16(20, 1, true);
            view.setUint16(22, 1, true);
            view.setUint32(24, sampleRate, true);
            view.setUint32(28, sampleRate * 2, true);
            view.setUint16(32, 2, true);
            view.setUint16(34, 16, true);
            writeString(36, 'data');
            view.setUint32(40, samples * 2, true);
            
            // 生成正弦波数据
            for (let i = 0; i < samples; i++) {
                const sample = Math.sin(2 * Math.PI * frequency * i / sampleRate) * 0.3 * this.volume;
                view.setInt16(44 + i * 2, sample * 32767, true);
            }
            
            // 创建Blob和URL
            const blob = new Blob([buffer], { type: 'audio/wav' });
            const url = URL.createObjectURL(blob);
            
            audio.src = url;
            audio.volume = this.volume;
            audio.play().then(() => {
                // 播放完成后清理URL
                setTimeout(() => URL.revokeObjectURL(url), duration + 100);
            }).catch(() => {
                // 如果还是失败，使用最简单的方法
                console.log('音效播放失败，使用静默模式');
            });
            
        } catch (error) {
            console.log('音效系统不可用:', error);
        }
    }

    // 播放音效
    playSound(soundName) {
        if (this.sounds[soundName] && this.enabled) {
            this.sounds[soundName]();
        }
    }

    // 设置音量
    setVolume(volume) {
        this.volume = Math.max(0, Math.min(1, volume));
    }

    // 启用/禁用音效
    setEnabled(enabled) {
        this.enabled = enabled;
    }

    // 检查音频支持
    isSupported() {
        return !!(window.AudioContext || window.webkitAudioContext || window.Audio);
    }
}

// 创建全局音频系统实例
window.simpleAudioSystem = new SimpleAudioSystem();